<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
</head>
<body>
<div class="container">
    <h2>用户登录</h2>
    <form id="login-form">
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" required>
        </div>
        <div class="form-group">
            <label for="captcha">验证码</label>
            <input type="text" id="captcha" name="captcha" required>
            <img id="captcha-img" src="" alt="验证码">
            <button type="button" id="refresh-captcha">刷新</button>
        </div>
        <button type="submit">登录</button>
    </form>
</div>

<script>
    let sessionId = ''; // 用于存储 Session ID

    // 获取验证码
    async function getCaptcha() {
        try {
            const response = await fetch('http://localhost:8001/api/users/captcha');

            // 检查 HTTP 状态码是否为 2xx
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }

            const data = await response.json();

            if (data.code === "200") {
                // 修正：直接使用 data.captchaImage
                document.getElementById('captcha-img').src = data.captchaImage;
                sessionId = data.sessionId; // 存储 Session ID
                console.log('Generated captcha, session ID: ' + sessionId);
            } else {
                alert(data.msg || "验证码生成失败");
            }
        } catch (error) {
            console.error('获取验证码失败:', error);
            alert('获取验证码失败，请重试');
        }
    }

    // 刷新验证码
    document.getElementById('refresh-captcha').addEventListener('click', getCaptcha);

    // 初始加载验证码
    window.addEventListener('load', getCaptcha);

    // 提交登录表单
    document.getElementById('login-form').addEventListener('submit', async function(event) {
        event.preventDefault();
        const formData = new FormData(event.target);
        const userData = {
            username: formData.get('username'),
            password: formData.get('password'),
            captcha: formData.get('captcha'),
            sessionId: sessionId // 传递 Session ID
        };

        try {
            const response = await fetch('http://localhost:8001/api/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(userData)
            });

            const data = await response.json();
            alert(data.msg);
        } catch (error) {
            console.error('登录失败:', error);
            alert('登录失败，请重试');
        }
    });
</script>
</body>
</html>